/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.govProcure.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.base.model.Category;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.Organization;
import com.yunhoo.base.model.Person;
import com.yunhoo.govProcure.db.dao.ProcureBudgetEditDao;
import com.yunhoo.govProcure.model.CateDataModel;
import com.yunhoo.govProcure.model.CateEditBase;
import com.yunhoo.govProcure.model.CateEditDetail;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.CommonParam;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.TreeRule;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.model.TreeNode;
import org.richfaces.model.TreeNodeImpl;

/**
 * 预算追加编制
 *
 * @author Administrator
 */
@ManagedBean(name = "budgetAddEditGovBean")
@SessionScoped
public class ProcureBudgetAddBean {

    private final static DaoManager daom = DaoConfig.getDaoManager();
    private static ProcureBudgetEditDao dao = (ProcureBudgetEditDao) daom.getDao(ProcureBudgetEditDao.class);
    //
    private final static String NAMESPACE = "budgetEditGov";
    private final static String NAME_SPACE = "budgetCheckGov";
    //
    private Organization org = null;
    private Integer iyear = 0;
    private List<Integer> yearli = CommonParam.yearListOfInteger();
    private List<SelectItem> selectNameli;
    //
    private CateEditBase base = null;
    private CateEditDetail detail = null;
    private List<CateEditDetail> detailli = new ArrayList<CateEditDetail>();
    private DataModel<CateEditDetail> detailModel = new ListDataModel<CateEditDetail>();
    private boolean addOrUpdate = false;
    private boolean editStatus = false;
    private boolean newBase = false;
    private boolean forStatus = false;
    private boolean forQuality = false;
    private List<FinancialProject> projList = new ArrayList<FinancialProject>();
    private DataModel<FinancialProject> projModel = new ListDataModel<FinancialProject>();
    private String quality = "";//采购预算资金性质
    private Category cate = new Category();
    private List<String> itemli = new ArrayList<String>();
    private TreeNode rootNode = null;//处室选择

    public ProcureBudgetAddBean() {
        initProjList();
        intiItemLi();
    }

    private void initStatus() {
        addOrUpdate = false;
        editStatus = false;
    }

    private void initProjList() {
        projList = CommonParam.financialProjectList();
        projModel.setWrappedData(projList);
    }

    private void intiItemLi() {
        itemli = dao.queryAllCategroyStandardCode();//特定类目 --> 规格要求
    }

    public void selectProject() {
        FinancialProject proj = projModel.getRowData();
        detail.setProject(proj);
    }

    public void orgSelected(TreeSelectionChangeEvent event) {
        org = (Organization) TreeUtil.listener(event);
    }

    public void cateSelected(TreeSelectionChangeEvent event) {
        cate = (Category) TreeUtil.listener(event);
        detail.setCate(cate);
        if (!Null.check(selectNameli)) {
            selectNameli.clear();
        }
        List<CateDataModel> list = new ArrayList<CateDataModel>();
        for (String item : itemli) {
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = dao.queryCategroyStandardByCategoryCode(item.trim());
            }
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = dao.queryCategroyStandardByCategoryCode(item.trim());
            }
            if (cate.getCode().trim().startsWith(item.trim())) {
                list = dao.queryCategroyStandardByCategoryCode(item.trim());
            }
            selectNameli = new ArrayList<SelectItem>();
            for (CateDataModel l : list) {
                selectNameli.add(new SelectItem(l.getItemCode(), l.getSelectName()));
            }
        }
        System.out.println("selectNameli1:" + selectNameli.size());
    }

    public void selected() {
        detail = detailModel.getRowData();
        if (!Null.check(selectNameli)) {
            selectNameli.clear();
        }
        List<CateDataModel> list = new ArrayList<CateDataModel>();
        if (!Null.check(detail.getAppend())) {
            for (String item : itemli) {
                if (detail.getCate().getCode().trim().startsWith(item.trim())) {
                    list = dao.queryCategroyStandardByCategoryCode(item.trim());
                }
                if (detail.getCate().getCode().trim().startsWith(item.trim())) {
                    list = dao.queryCategroyStandardByCategoryCode(item.trim());
                }
                if (detail.getCate().getCode().trim().startsWith(item.trim())) {
                    list = dao.queryCategroyStandardByCategoryCode(item.trim());
                }
                if (!Null.check(list)) {
                    selectNameli = new ArrayList<SelectItem>();
                    for (CateDataModel l : list) {
                        selectNameli.add(new SelectItem(l.getItemCode(), l.getSelectName()));
                    }
                }
            }
        }
    }

    public void queryList() {
        newBase = false;
        if (Null.check(iyear)) {
            ToolKit.msgs_err("请选择年度!");
        } else if (Null.check(quality)) {
            ToolKit.msgs_err("请选择采购预算资金性质!");
        } else {
            initList();
            initStatus();
        }
    }

    public void query() {
        newBase = false;
        if (Null.check(iyear)) {
            ToolKit.msgs_err("请选择年度!");
        } else if (Null.check(quality)) {
            ToolKit.msgs_err("请选择采购预算资金性质!");
        } else {
            initList();
            initStatus();
        }
        detail = new CateEditDetail();
    }

    private void initList() {
//        Map map = new HashMap();
//        //map.put("orgCode", getCurOrg().getCode().trim());
//        map.put("iyear", iyear);
//        map.put("deptCode", getCurDept().getCode().trim());
//        map.put("perNumber", getCurPer().getCpsn_number().trim());
//        map.put("addSign", "1");
//        base = (CateEditBase) dao.query(map, NAMESPACE);

        CateEditBase param = new CateEditBase(true);
        param.setIyear(iyear);
        param.setDeptCode(getCurDept().getCode().trim());
        param.setEditPerCode(getCurPer().getCpsn_number().trim());
        param.setAddSign("1");
        // base = (CateEditBase) dao.query(map, NAMESPACE);
        base = (CateEditBase) dao.queryCateEditBaseByDeptAndPerson(param);
        if (base != null) {
//            map.put("number", base.getNumber());
//            map.put("quality", quality);
//            detailli = dao.queryList(map, NAMESPACE);
            CateEditDetail param1 = new CateEditDetail();
            param1.setOrgCode(LoginParam.getOrg().getCode());
            param1.setIyear(iyear);
            param1.setNumber(base.getNumber());
            param1.setQuality(quality);
            detailli = dao.queryListCateEditDetailByNumber(param1);
        } else {
            newBase = true;
            base = new CateEditBase(true);
            base.setNumber(maxCode());
            base.setIyear(iyear);
            base.setDataPeriod(String.valueOf(iyear));
            base.setDeptCode(getCurDept().getCode());
            base.setEditPerCode(getCurPer().getCpsn_number());
            base.setEditDate(new Date());
            base.setAddSign("1");
        }
        detailModel.setWrappedData(detailli);
    }

    public void add() {
        if (Null.check(iyear) || Null.check(quality)) {
            ToolKit.msgs_err("请先选择点击查询!");
        } else {
            addOrUpdate = true;
            editStatus = true;
            detail = new CateEditDetail();
            detail.setNumber(base.getNumber());
        }
    }

    public void update() {
        addOrUpdate = false;
        editStatus = true;
    }

    public void delete() throws SQLException {
        dao.deleteCateEditDetailById(detail);
        detail = new CateEditDetail();
        ToolKit.msgs_err("删除成功!");
        queryList();
        initStatus();
    }

    public void checkSave() throws SQLException {
        if (detail.getCate() == null || Null.check(detail.getCate().getCode())) {
            ToolKit.msgs_err("请选择品目!");
        } else if (Null.check(detail.getCate().getCount())) {
            ToolKit.msgs_err("请填写采购数量!");
        } else if (Null.check(detail.getFinancial()) && Null.check(detail.getOther())) {
            ToolKit.msgs_err("请至少填写一个资金来源!");
        } else if (Null.check(detail.getOrganizeForm())) {
            ToolKit.msgs_err("请选择组织形式!");
        } else if (Null.check(detail.getCateWay())) {
            ToolKit.msgs_err("请选择采购方式!");
        } else if (quality.equals("1") && Null.check(detail.getProject().getFinCode())) {
            ToolKit.msgs_err("请选择项目!");
        } else if (!Null.check(selectNameli) && Null.check(detail.getAppend())) {
            ToolKit.msgs_err("请选择附加信息!");
        } else {
            if (quality.equals("0")) {
                detail.getProject().setFinCode("");
            }
            save();
            queryList();
            initStatus();
        }
    }

    private void save() throws SQLException {
        detail.setFinancial(Null.convert(detail.getFinancial()));
        detail.setOther(Null.convert(detail.getOther()));
        detail.setQuality(quality);
        detail.setStatus("0");
        if (!newBase) {
            if (addOrUpdate) {
                detail.setId(maxCodeId());
                dao.insertCateEditDetail(detail);
            } else {
                if (quality.equals("1")) {
                    dao.updateCateEditDetailById(detail);
                }
                if (quality.equals("0")) {
                    detail.getProject().setFinCode("");
                    dao.updateCateEditDetailById(detail);
                    detail.setProject(null);
                }
            }
        } else if (newBase) {
            try {
                daom.startTransaction();
                detail.setId(maxCodeId());
                dao.insertCateEditBase(base);
                dao.insertCateEditDetail(detail);
                daom.commitTransaction();
            } finally {
                daom.endTransaction();
            }
            newBase = false;
        }
    }

    public void cancel() {
        if (addOrUpdate) {
            detail = new CateEditDetail();
        }
        initStatus();
    }

    public void submitFor() throws SQLException {
        detail.setCheckNumber("");
        detail.setStatus("1");
        dao.updateCateEditDetailById(detail);
        ToolKit.msgs_err("提交完成!");
        queryList();
        initStatus();
    }

    public void canclFor() throws SQLException {
        detail.setStatus("0");
        dao.updateCateEditDetailById(detail);
        ToolKit.msgs_err("撤单成功!");
        queryList();
        initStatus();
    }

    public void qualityChange() {
        if (quality.equals("0")) {
            detail.setProject(null);
        }
    }

    public void changeListener() {
        ToolKit.msgs_err("请单击查询");
    }

    private Person getCurPer() {
        return LoginParam.getPer();
    }

    private Department getCurDept() {
        return LoginParam.getDept();
    }

    private String maxCode() {
        Integer maxCode = (Integer) dao.queryMaxNumberFromBase();
        if (maxCode == null) {
            maxCode = 0;
        }
        return String.format(iyear + "YS-%08d%n", maxCode + 1).trim();
    }

    private Integer maxCodeId() {
        Integer maxCodeId = (Integer) dao.queryMaxNumberFromDetail();
        if (maxCodeId == null) {
            maxCodeId = 0;
        }
        return maxCodeId + 1;
    }

    public void treeSelected(TreeSelectionChangeEvent event) {
        Department temp = (Department) TreeUtil.listener(event);
        detail.setOfficeCode(temp.getCode());
        detail.setOfficeName(temp.getName());
    }

    public TreeNode getRootNode() {
        if (this.rootNode == null) {
            loadTree();
        }
        return rootNode;
    }

    private void loadTree() {
        rootNode = new TreeNodeImpl();

        List<Department> list = IbatisTemplate.queryForList("procureBudgetEdit.queryListForOffice", new Department(true));

        TreeUtil.addNode(list, rootNode, TreeRule.getDepartmentTreeRule());
    }

    public static ProcureBudgetEditDao getDao() {
        return dao;
    }

    public static void setDao(ProcureBudgetEditDao dao) {
        ProcureBudgetAddBean.dao = dao;
    }

    public Organization getOrg() {
        return org;
    }

    public void setOrg(Organization org) {
        this.org = org;
    }

    public Integer getIyear() {
        return iyear;
    }

    public void setIyear(Integer iyear) {
        this.iyear = iyear;
    }

    public List<Integer> getYearli() {
        return yearli;
    }

    public void setYearli(List<Integer> yearli) {
        this.yearli = yearli;
    }

    public List<SelectItem> getSelectNameli() {
        return selectNameli;
    }

    public void setSelectNameli(List<SelectItem> selectNameli) {
        this.selectNameli = selectNameli;
    }

    public CateEditBase getBase() {
        return base;
    }

    public void setBase(CateEditBase base) {
        this.base = base;
    }

    public CateEditDetail getDetail() {
        return detail;
    }

    public void setDetail(CateEditDetail detail) {
        this.detail = detail;
    }

    public List<CateEditDetail> getDetailli() {
        return detailli;
    }

    public void setDetailli(List<CateEditDetail> detailli) {
        this.detailli = detailli;
    }

    public DataModel<CateEditDetail> getDetailModel() {
        return detailModel;
    }

    public void setDetailModel(DataModel<CateEditDetail> detailModel) {
        this.detailModel = detailModel;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isEditStatus() {
        return editStatus;
    }

    public void setEditStatus(boolean editStatus) {
        this.editStatus = editStatus;
    }

    public boolean isNewBase() {
        return newBase;
    }

    public void setNewBase(boolean newBase) {
        this.newBase = newBase;
    }

    public boolean isForStatus() {
        return forStatus;
    }

    public void setForStatus(boolean forStatus) {
        this.forStatus = forStatus;
    }

    public boolean isForQuality() {
        return forQuality;
    }

    public void setForQuality(boolean forQuality) {
        this.forQuality = forQuality;
    }

    public List<FinancialProject> getProjList() {
        return projList;
    }

    public void setProjList(List<FinancialProject> projList) {
        this.projList = projList;
    }

    public DataModel<FinancialProject> getProjModel() {
        return projModel;
    }

    public void setProjModel(DataModel<FinancialProject> projModel) {
        this.projModel = projModel;
    }

    public String getQuality() {
        return quality;
    }

    public void setQuality(String quality) {
        this.quality = quality;
    }

    public Category getCate() {
        return cate;
    }

    public void setCate(Category cate) {
        this.cate = cate;
    }

    public List<String> getItemli() {
        return itemli;
    }

    public void setItemli(List<String> itemli) {
        this.itemli = itemli;
    }
}
